package com.wyvoid.forum.web.action.user;

import net.sourceforge.stripes.action.*;
import net.sourceforge.stripes.validation.*;
import net.sourceforge.stripes.integration.spring.SpringBean;
import com.wyvoid.forum.domain.User;
import com.wyvoid.forum.domain.SessionUser;
import com.wyvoid.forum.web.action.BaseAction;
import com.wyvoid.forum.service.IUserService;
import com.wyvoid.forum.exception.user.PasswordFailureException;
import com.wyvoid.forum.exception.user.UsernameNotFoundException;
import com.wyvoid.forum.util.ForumUtil;
import com.wyvoid.forum.Constant;
import com.wyvoid.core.util.CookieUtils;
import com.wyvoid.core.util.DesCryptUtil;
import org.apache.commons.lang.StringUtils;

import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * <p>51void.com</p>
 * User:cjp
 * Date: 2007-5-14
 * Time: 21:58:24
 */
@UrlBinding("/user/login.do")
public class LoginAction extends BaseAction implements ValidationErrorHandler {
    @ValidateNestedProperties({
    @Validate(field = "username", required = true, minlength = 2, maxlength = 32),
    @Validate(field = "password", required = true, minlength = 4, maxlength = 16)
            })
    private User user;
    @Validate(required = true, minlength = 4, maxlength = 4)
    private String validateCode;
    private int cookie;
    private int online;
    @SpringBean
    private IUserService userService;

    public void setUser(User user) {
        this.user = user;
    }


    public User getUser() {
        return user;
    }

    public String getValidateCode() {
        return validateCode;
    }

    public void setValidateCode(String validateCode) {
        this.validateCode = validateCode;
    }

    public int getCookie() {
        return cookie;
    }

    public void setCookie(int cookie) {
        this.cookie = cookie;
    }

    public int getOnline() {
        return online;
    }

    public void setOnline(int online) {
        this.online = online;
    }

    public void setUserService(IUserService userService) {
        this.userService = userService;
    }

    @DefaultHandler
    public Resolution login() {
        try {
            User curUser = userService.loginUser(user.getUsername(), user.getPassword());
            if (cookie > 0) {
                int cookieAge = 0;
                int oneDaySeconds = 60 * 60 * 24;
                if (cookie == 1) {
                    cookieAge = oneDaySeconds;
                } else if (cookie == 2) {
                    cookieAge = 30 * oneDaySeconds;
                } else if (cookie == 3) {
                    cookieAge = 365 * oneDaySeconds;
                }
                String value = curUser.getUsername() + "|" + curUser.getPassword()+"|"+online;
                try {
                    value = DesCryptUtil.encrypt(value, (String) ForumUtil.settings.get("cookiekey"));
                    CookieUtils.addCookie(context.getResponse(), Constant.cookieName, value, cookieAge, null);
                } catch (Exception e) {
                    log.warn("cookie 加密失败");
                }
            }
            SessionUser sessionUser = new SessionUser(curUser.getId(), curUser.getNickname(),online);
            Date now = new Date();
            curUser.setLastLoginIp(context.getRequest().getRemoteAddr());
            sessionUser.setLastLoginTime(curUser.getLastLoginTime());
            curUser.setLastLoginTime(now);
            userService.updateUser(curUser);

            getContext().setUser(sessionUser);
            String forward = context.getRequest().getParameter("forward");
            if (StringUtils.isNotBlank(forward)) {
                return new RedirectResolution(forward, false);
            } else {
                return new RedirectResolution("/");
            }
        } catch (PasswordFailureException e) {
            ValidationError error = new LocalizableError("incorrectPassword");
            getContext().getValidationErrors().add("user.password", error);
            return getContext().getSourcePageResolution();
        } catch (UsernameNotFoundException e) {
            ValidationError error = new LocalizableError("usernameDoesNotExist", user.getUsername());
            getContext().getValidationErrors().add("user.username", error);
            return getContext().getSourcePageResolution();
        }


    }

    @DontValidate
    public Resolution loginForm() {
        String forward = context.getRequest().getParameter("forward");
        if (forward == null) {
            forward = context.getRequest().getHeader("referer");
        }
        if (forward == null) {
            forward = getForwardUrl();
        }
        if (StringUtils.indexOf(forward, "/user/") == -1) {
            context.getRequest().setAttribute("forward", forward);
        }
        return getBBSResolution("user/loginForm");
    }

    @ValidationMethod(on = "login")
    public void confirmValidateCode(ValidationErrors errors) {
        if (!StringUtils.equals(validateCode, (String) context.getSessionAttribute("validateCode"))) {
            errors.add("validateCode", new SimpleError("验证码填写错误"));
        }
    }

    public Resolution handleValidationErrors(ValidationErrors validationErrors) throws Exception {
        return loginForm();
    }

    @DontValidate
    public Resolution markread(){
        HttpServletResponse response=context.getResponse();
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        SessionUser sessionUser = context.getUser();
        if (sessionUser != null) {
            Date now=new Date();
            sessionUser.setLastLoginTime(now);
            User user=userService.getUser(sessionUser.getId());
            if(user!=null){
                userService.updateUser(user);
            }
        }

        String targetUrl = context.getRequest().getParameter("referer");
        if (targetUrl == null) {
            targetUrl = context.getRequest().getHeader("referer");
        }
        if (StringUtils.isNotBlank(targetUrl) && targetUrl.indexOf("leftMenu.do") == -1) {
            return new RedirectResolution(targetUrl, false).addParameter("ra",Math.random());
        } else {
            return new RedirectResolution("/").addParameter("ra",Math.random());
        }
    }
}
